'''
1、登录获取token
2、访问接口，获取返回值。
'''
import requests
import json


def firstTest(headerData):
    '''
    :param headerData:
    :return:
    测试验证是否有效
    '''
    print("------验证token是否有效-------")
    getAuth = requests.post(orignalUrl + tokenUrl, headers=headerData)
    if getAuth.status_code != 200:
        return False
    return True

# 初始url
orignalUrl = "http://192.168.17.247:9998"
tokenUrl = "/token"
urlSet = ["/api/Classes/GetClasses", "/api/Course/AddAnswerRecord",
          "/api/Course/AddCourseEvaluate", "/api/Course/AddVideoNote", "/api/Course/DelVideoNote",
          "/api/Course/EditVideoNote", "/api/Course/GetCourseByClassesID", "/api/Course/GetCourseEvaluate",
          "/api/Course/GetCourseExquisite", "/api/Course/GetCoursePPT", "/api/Course/GetCourseProblems",
          "/api/Course/GetCourseVideo", "/api/Course/GetFreeCourses", "/api/Course/GetHotCourses",
          "/api/Course/GetRelatedCourses", "/api/Course/GetStudyRecord", "/api/Course/GetVideoNotes",
          "/api/sign", "/api/Book/GetBooks"]
loginInfo = {"grant_type": "1", "username": "18576444111", "password": "XC6gKhlZtH1ZCLv+ooi0I5LwBvLvC2kzfwz5iPBS6QQI5DXSbkpg8ExSKeuzI48xfhIIL+3q6WIL6ajfIKsrvQ=="}
# 访问文件-1、创建文件 2、读取数据- 11、写入数据 21、访问网页，返回是否正确 -211、结束 212、删除文件 返回1
try:
    print("------读取文件中的token-------")
    f = open(r'data.txt', 'r')
    authroize = f.read()
    print("------读取token成功-------")
except:
    print("------读取文件中的token失败，开始获取token-------")
    f = open(r'data.txt', 'w')
    getAuth = requests.post(orignalUrl + tokenUrl, data=loginInfo)
    authr = json.loads(getAuth.text)
    authroize = authr['data']['access_token']
    f.write(authroize)
    print("------获取token成功，保存在data.txt文件中-------")

head = {"Authorization": authroize}

if firstTest(head):
    print("------token有效，开始进行接口测试-------")
    # 进行其它接口验证
    pass
else:
    print("------token无效，开始重新获取token-------")
    # 获取新的验证码，保存到文件加里面，并进行测试
    pass